<template>
  <div class="title">
    <img class="bannerImg" src="@/assets/image/register.png" alt="" />
    <div class="bannerDiv"></div>
    <span>剑桥MSE英语五级考试报考信息</span>
  </div>
  <div class="cantainer">
    <div class="titleText">请如实填写您的个人信息：</div>
    <div class="content">
      <a-form ref="formRef" :model="formState" :rules="rules">
        <a-form-item ref="nickname" label="考生姓名" name="nickname">
          <a-input
            v-model:value="formState.nickname"
            placeholder="请输入姓名"
          />
        </a-form-item>

        <a-form-item ref="nickname_py" label="考生拼音" name="nickname_py">
          <a-input
            v-model:value="formState.nickname_py"
            placeholder="请输入姓名拼音"
          />
        </a-form-item>

        <a-form-item label="性别" name="gender">
          <a-select v-model:value="formState.gender" placeholder="请选择性别">
            <a-select-option value="0">女</a-select-option>
            <a-select-option value="1">男</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item ref="birthday" label="出生日期" name="birthday">
          <a-date-picker
            v-model:value="formState.birthday"
            type="date"
            format="YYYY-MM-DD"
            placeholder="请选择出生日期"
            style="width: 100%"
            @change="panelChange1"
          />
        </a-form-item>

        <a-form-item ref="username" label="身份证号" name="username">
          <a-input
            v-model:value="formState.username"
            placeholder="请输入身份证号"
          />
        </a-form-item>

        <a-form-item ref="avatar" label="照片（电子版）" name="avatar">
          <a-upload
            v-model:file-list="fileList"
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :before-upload="beforeUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
            <div v-else>
              <loading-outlined v-if="loading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">点击上传</div>
            </div>
          </a-upload>
        </a-form-item>

        <a-form-item ref="mobile" label="联系方式" name="mobile">
          <a-input
            v-model:value="formState.mobile"
            placeholder="请输入联系方式"
          />
        </a-form-item>

        <a-form-item ref="email" label="邮箱地址" name="email">
          <a-input-search
            v-model:value="formState.email"
            placeholder="请输入邮箱地址"
            enter-button="获取验证码"
            size="large"
            @search="onSearch"
          />
        </a-form-item>

        <a-form-item ref="code" label="邮箱验证码" name="code">
          <a-input
            v-model:value="formState.code"
            placeholder="请输入邮箱验证码"
          />
        </a-form-item>

        <a-form-item ref="huji" label="户籍" name="huji">
          <a-input v-model:value="formState.huji" placeholder="请输入户籍" />
        </a-form-item>

        <a-form-item ref="address" label="家庭住址" name="address">
          <a-input
            v-model:value="formState.address"
            placeholder="请输入家庭住址"
          />
        </a-form-item>

        <a-form-item ref="school" label="目前就读学校/培训机构" name="school">
          <a-input
            v-model:value="formState.school"
            placeholder="请输入目前就读学校/培训机构"
          />
        </a-form-item>

        <a-form-item
          ref="username_endtime"
          label="证件有效期"
          name="username_endtime"
        >
          <a-date-picker
            v-model:value="formState.username_endtime"
            type="date"
            format="YYYY-MM-DD"
            placeholder="请选择证件有效期"
            style="width: 100%"
            :disabled-date="disabledDate"
            :disabled-time="disabledDateTime"
            :show-time="{ defaultValue: moment('HH:mm:ss') }"
            @change="panelChange2"
          />
        </a-form-item>

        <a-form-item ref="password" label="密码设置" name="password">
          <a-input
            v-model:value="formState.password"
            type="password"
            placeholder="请输入密码"
          />
        </a-form-item>

        <a-form-item ref="passwordone" label="确认密码" name="passwordone">
          <a-input
            v-model:value="formState.passwordone"
            type="password"
            placeholder="请再次确认密码"
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="onSubmit" class="button"
            >提 交</a-button
          >
        </a-form-item>
      </a-form>
      <div class="buttons" @click="$emit('registerFn')">返回登录</div>
    </div>
  </div>
  <Footer />
  <teleport to="body">
    <div v-if="modalOpen" class="modal">
      <div>三秒后自动跳转，请勿操作...</div>
    </div>
  </teleport>
</template>

<script>
import moment from "moment";
import { defineComponent, reactive, ref } from "vue";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";
import Footer from "@/components/Footer.vue";
import {
  uploadImg,
  imgUrl,
  setUserRegister,
  setUserLogin,
  getSend,
} from "@/api/https.js";
export default defineComponent({
  setup() {
    const formRef = ref();
    const router = useRouter();
    const formState = reactive({
      nickname: "", // 考生姓名
      nickname_py: "", // 考生拼音
      gender: null, // 性别
      birthday: null, // 出生日期
      username: "", // 身份证号
      avatar: "", // 照片（电子版）
      mobile: "", // 联系方式
      email: "", // 邮箱地址
      code: "", //邮箱验证码
      huji: "", // 户籍
      address: "", // 家庭住址
      school: "", // 目前就读学校/培训机构
      username_endtime: null, //证件有效期
      password: "", //密码
      passwordone: "", //确认密码
    });
    // 身份证正则
    let validatePass = async (rule, value) => {
      console.log("正则---", value);
      const zz = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (!zz.test(value)) {
        return Promise.reject("身份证格式填写错误");
      } else {
        return Promise.resolve();
      }
    };
    // 电话正则
    let phoneZZ = async (rule, value) => {
      const zz = /^1[3456789]\d{9}$/;
      if (!zz.test(value)) {
        return Promise.reject("手机号格式错误");
      } else {
        return Promise.resolve();
      }
    };
    // 邮箱正则
    let emailZZ = async (rule, value) => {
      const zz =
        /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/;
      if (!zz.test(value)) {
        return Promise.reject("邮箱格式错误");
      } else {
        return Promise.resolve();
      }
    };
    // 二次密码验证
    let passwordZZ = async () => {
      if (formState.password !== formState.passwordone) {
        return Promise.reject("两次密码输入不一致");
      } else {
        return Promise.resolve();
      }
    };

    const onSearch = async () => {
      if (formState.email == "") return message.success("请填写邮箱地址!!!");
      const params = {
        email: formState.email,
        event: "register",
      };
      const data = await getSend(params);
      data.code == 1 ? message.success(data.msg) : message.error(data.msg);
      console.log("获取验证码---", data);
    };

    const range = (start, end) => {
      const result = [];

      for (let i = start; i < end; i++) {
        result.push(i);
      }

      return result;
    };
    const disabledDate = (current) => {
      return current && current < moment().endOf("day");
    };

    const disabledDateTime = () => {
      return {
        disabledHours: () => range(0, 24).splice(4, 20),
        disabledMinutes: () => range(30, 60),
        disabledSeconds: () => [55, 56],
      };
    };
    const rules = {
      nickname: [
        {
          required: true,
          message: "请输入姓名",
          trigger: "blur",
        },
      ],
      nickname_py: [
        {
          required: true,
          message: "请输入姓名",
          trigger: "blur",
        },
      ],
      gender: [
        {
          required: true,
          message: "请选择性别",
          trigger: "blur",
        },
      ],
      birthday: [
        {
          required: true,
          message: "请选择出生日期",
          trigger: "change",
        },
      ],
      username: [
        {
          required: true,
          message: "请输入身份证号",
          trigger: "blur",
        },
        {
          validator: validatePass,
          trigger: "blur",
        },
      ],
      avatar: [
        {
          required: true,
          message: "请上传照片",
          trigger: "blur",
        },
      ],
      mobile: [
        {
          required: true,
          message: "请输入联系方式",
          trigger: "blur",
        },
        {
          validator: phoneZZ,
          trigger: "blur",
        },
      ],
      email: [
        {
          required: true,
          message: "请输入邮箱地址",
          trigger: "blur",
        },
        {
          validator: emailZZ,
          trigger: "blur",
        },
      ],
      code: [
        {
          required: true,
          message: "请输入邮箱验证码",
          trigger: "blur",
        },
      ],
      huji: [
        {
          required: true,
          message: "请输入户籍",
          trigger: "blur",
        },
      ],
      address: [
        {
          required: true,
          message: "请输入家庭住址",
          trigger: "blur",
        },
      ],
      school: [
        {
          required: true,
          message: "请输入目前就读学校/培训机构",
          trigger: "blur",
        },
      ],
      username_endtime: [
        {
          required: true,
          message: "请选择证件有效期",
          trigger: "change",
        },
      ],
      password: [
        {
          required: true,
          message: "请输入密码",
          trigger: "blur",
        },
        {
          min: 6,
          max: 13,
          message: "请填写6-13位密码",
          trigger: "blur",
        },
      ],
      passwordone: [
        {
          required: true,
          message: "请再次输入密码",
          trigger: "blur",
        },
        {
          validator: passwordZZ,
          trigger: "blur",
        },
      ],
    };

    const modalOpen = ref(false);

    const onSubmit = async () => {
      formRef.value
        .validate()
        .then(async () => {
          const data = await setUserRegister(formState);
          if (data.code == 1) {
            message.success(`${data.msg}`);
            getUser();
          } else {
            message.error(`${data.msg}`);
          }
        })
        .catch((error) => {
          console.log("error", error);
        });
    };

    const getUser = async () => {
      modalOpen.value = true;
      const params = {
        account: formState.username, // 证件号
        password: formState.password, // 证件号
      };
      const data = await setUserLogin(params);
      if (data.code == 1) {
        message.success(`${data.msg}`);
        localStorage.setItem("info", JSON.stringify(data.data.userinfo));
        localStorage.setItem("token", JSON.stringify(data.data.userinfo.token));
        setTimeout(() => {
          modalOpen.value = false;
          router.push({
            name: "Home",
          });
        }, 2000);
      } else {
        message.error(`${data.msg}`);
        location.reload();
      }

      console.log(data);
    };

    const fileList = ref([]);
    const loading = ref(false);
    const imageUrl = ref("");

    const beforeUpload = async (file) => {
      let param = new FormData();
      param.append("file", file);
      const data = await uploadImg(param);
      formState.avatar = data.data.url;
      imageUrl.value = imgUrl + data.data.url;
      message.info(`${data.msg}`);
      console.log("图片上传---", data);
    };

    const panelChange1 = (val, mode) => {
      formState.birthday = mode;
    };

    const panelChange2 = (val, mode) => {
      formState.username_endtime = mode;
      console.log(formState.username_endtime);
    };

    return {
      formRef,
      other: "",
      formState,
      rules,
      onSubmit,
      fileList,
      beforeUpload,
      imageUrl,
      loading,
      panelChange1,
      panelChange2,
      modalOpen,
      disabledDate,
      disabledDateTime,
      moment,
      onSearch,
    };
  },
  components: {
    Footer,
  },
});
</script>

<style lang="less" scoped>
.title {
  position: relative;
  background-color: rosybrown;
  color: #fff;
  font-weight: 800;
  letter-spacing: 1px;
  font-size: var(--bannerSize);

  .bannerImg {
    width: 100%;
    display: var(--bannerImgBool);
  }
  .bannerDiv {
    width: 100%;
    height: 230px;
    background-image: url(../../assets/image/register.png);
    background-repeat: no-repeat;
    background-size: auto 100%;
    background-position: center;
    display: var(--bannerDivBool);
  }
  span {
    display: block;
    width: 100%;
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
.cantainer {
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.24);
  border-radius: 20px;
  width: 100%;
  padding: 30px;
  max-width: 1248px;
  position: relative;
  top: var(--bannerTop);
  left: 50%;
  transform: translateX(-50%);
  background-color: #fff;

  .titleText {
    border-bottom: 1px solid #e6e6e6;
    padding-bottom: 20px;
    font-size: 1.37rem;
    font-family: PingFang SC;
    font-weight: 500;
    color: #333333;
  }

  .content {
    position: relative;
    left: 50%;
    transform: translateX(-50%);
    max-width: 500px;
    margin-top: 40px;

    .ant-form-item {
      flex-direction: var(--bannerFlex);
      justify-content: center;
    }

    .button {
      margin-top: 20px;
      width: 100%;
      height: 45px;
      background: #554de6;
      border-radius: 25px;
      font-size: var(--txtSize);
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #ffffff;
    }

    .buttons {
      text-align: center;
      font-size: var(--txtSize);
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #808080;
      cursor: pointer;
    }

    /deep/ .ant-col {
      width: 300px;
    }
    /deep/ .ant-form-item-label {
      width: 140px;
      margin-right: 20px;
    }
  }
}
/deep/ .ant-modal-confirm-btns {
  display: none;
}
.modal {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  //   top: 50%;
  //   left: 50%;
  //   transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.459);

  div {
    width: 80%;
    max-width: 400px;
    height: 200px;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border-radius: 20px;
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 1rem;
    font-weight: 700;
    letter-spacing: 1px;
  }
}
/deep/ .ant-btn-primary {
  background: #554de6;
  border-radius: 17px;
}
</style>
